package cc.ysblog.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.dorje.sys.bean.MenuLeftBean;
import com.dorje.sys.entity.Menu;


public class TreeUtil {
	
	
	public static List<Menu> getMenuTree(List<Menu> menus){
		List<Menu> rootMenus = new ArrayList<Menu>();
		for(Menu menu : menus){
			if(menu.getPid() == 0 ){
				rootMenus.add(menu);
			}
			for(Menu m:menus){
				if(m.getPid() == menu.getId()){
					if(menu.getChildren() == null){
						List<Menu> myChildrens = new ArrayList<Menu>();
						myChildrens.add(m);
						menu.setChildren(myChildrens);
					}else{
						menu.getChildren().add(m);
					}
				}
			}
		}	
		
		return rootMenus;
	}
	
	public static List<HashMap> getLeftMenuTree(List<MenuLeftBean> menus){
		List<MenuLeftBean> rootMenus = new ArrayList<MenuLeftBean>();
		for(MenuLeftBean menu : menus){
			if(menu.getPid() == 0 ){
				rootMenus.add(menu);
			}
			for(MenuLeftBean m:menus){
				if(m.getPid() == menu.getId()){
					if(menu.getChildren() == null){
						List<MenuLeftBean> myChildrens = new ArrayList<MenuLeftBean>();
						myChildrens.add(m);
						menu.setChildren(myChildrens);
					}else{
						menu.getChildren().add(m);
					}
				}
			}
		}			
		List<HashMap> maps = new ArrayList<HashMap>();
		for(MenuLeftBean menu:rootMenus){
			maps.add(Bean2Map(menu));
		}
		return maps;
	}
	
	private static HashMap Bean2Map(MenuLeftBean menu){
		HashMap<String,Object> map = new HashMap<String,Object>();
		map.put("id", menu.getId());
		map.put("text", menu.getText());
		map.put("selected", menu.isSelected());
		map.put("checked", menu.isChecked());
		
		if("/#".contentEquals(menu.getUrl()) || (menu.getChildren()!= null && menu.getChildren().size() > 0)){
			List<HashMap> children =new ArrayList<HashMap>();
			for(MenuLeftBean m:menu.getChildren()){
				children.add(Bean2Map(m));
			}
			map.put("children", children);
		}else{
			HashMap<String,String> url = new HashMap<String,String>();
			url.put("url", menu.getUrl());
			map.put("attributes", url);
		}		
		System.out.println(map);
		return map;
	}
}
